package cn.felord.common.controller.endpoints;

import cn.felord.common.bean.IdentifierEnum;
import cn.felord.common.bean.Rest;
import cn.felord.common.bean.RestBody;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 404  500 等错误 控制器.
 *
 * @author Dax
 * @since 10 :39  2018/9/17
 */
@RestController
@RequestMapping("/error")
public class CustomErrorController implements ErrorController {

    /**
     * Error rest.
     *
     * @param request the request
     * @return the rest
     */
    @RequestMapping
    public Rest error(HttpServletRequest request) {
        HttpStatus httpStatus = this.getStatus(request);
        int status = httpStatus.value();
        Map<String, Object> map = new HashMap<>();
        map.put("uri", attribute(request, ErrorRequestAttributeEnum.REQUEST_URI));
        map.put("errorMessage", attribute(request, ErrorRequestAttributeEnum.MESSAGE));
        map.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return RestBody.build(status, map, httpStatus.getReasonPhrase(), IdentifierEnum.DISABLE);
    }

    /**
     * Gets status.
     *
     * @param request the request
     * @return the status
     */
    protected HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) attribute(request, ErrorRequestAttributeEnum.STATUS_CODE);
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }


    private static Object attribute(HttpServletRequest request, ErrorRequestAttributeEnum attributeEnum) {
        return request.getAttribute(attributeEnum.attributeName());
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }


    /**
     * 错误请求参数枚举.
     *
     * @see HttpServletRequest#getAttribute(String)
     */
    enum ErrorRequestAttributeEnum {
        /**
         * 该属性给出状态码，状态码可被存储 type {@link Integer}.
         */
        STATUS_CODE("status_code"),
        /**
         * 该属性给出异常类型的信息，异常类型可被存储 type {@link Class}.
         */
        EXCEPTION_TYPE("exception_type"),
        /**
         * 该属性给出确切错误消息的信息，信息可被存储 type {@link String}.
         */
        MESSAGE("message"),
        /**
         * 该属性给出有关URL调用Servlet的信息，信息可被存储 type {@link String}.
         */
        REQUEST_URI("request_uri"),
        /**
         * 该属性给出异常产生的信息，信息可被存储 type {@link Throwable}.
         */
        EXCEPTION("exception"),
        /**
         * 该属性给出Servlet的名称，名称可被存储 type {@link String}.
         */
        SERVLET_NAME("servlet_name");


        private String value;
        private static final String PREFIX = "javax.servlet.error.";

        ErrorRequestAttributeEnum(String value) {
            this.value = value;
        }

        public String attributeName() {
            return PREFIX + this.value;
        }
    }
}
